/*
 * @Author: xuxu12138 1718324422@qq.com
 * @Date: 2022-10-15 16:02:02
 * @LastEditors: xuxu12138 1718324422@qq.com
 * @LastEditTime: 2024-09-03 09:58:12
 * @FilePath: /things-admin/src/view/role/bloc/FormSettingBloc.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import {deleteRole, getRole, postRole, putRole, putRoleRes} from '@/base/api/RoleApi';
import {Role} from '@/base/model/Role';
import {Resource} from '@/base/model/Resource';
import {getResourceMeg, getResourceMegId} from '@/base/api/ResourceApi';

export class FormSettingBloc {
  role = new Role();
  resourceAll: Array<Resource> = [];
  resourceItems: Array<Resource> = [];
  loading = false;
  isShowRoleModal = false;
  itemsArr: any = [];

  load(id: number, isAdd: boolean) {
    return getRole(id)
      .then((res) => {
        this.role = res.data;
        return getResourceMeg();
      }).then((res) => {
        // @ts-ignore
        console.log(res.data)
        this.resourceAll = res.data;
        this.getItemsArr();
        if (!isAdd) this.loadReSource(id);
        return res;
      });
  }

  loadReSource(id: number) {
    return getResourceMegId({id})
      .then((res) => {
        // @ts-ignore
        this.resourceItems = res.data;
        this.handleAlreadyItems();
        return res;
      });
  }

  getItemsArr() {
    const mainItems = this.resourceAll.filter(x => x.parentId === '0');
    mainItems.forEach(x => {
      this.itemsArr.push({parent: x, value: [], data: this.resourceAll.filter(j => j.parentId === x.id)});
    });
    console.log(this.itemsArr)
  }

  handleAlreadyItems() {
    this.itemsArr.forEach(x => {
      x.value = this.resourceItems.filter(j => j.parentId === x.parent.id).map(x => x.id);
    });
  }

  save(id: number | '') {
    const entity = {
      name: this.role.name,
      description: this.role.description
      // res: this.itemsArr.map(x => x.value)
    };
    return id ? putRole(id, entity) : postRole(entity);
  }

  saveRes(id: number) {
    const entity = {
      id,
      res: this.itemsArr.map(x => x.value)
    };
    return putRoleRes(entity)
  }

  changeRoleModal() {
    this.isShowRoleModal = !this.isShowRoleModal;
  }

}
